<?php

/**
 * comment actions.
 *
 * @package    simpleguestbook-symfony
 * @subpackage comment
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 8507 2008-04-17 17:32:20Z fabien $
 */
class commentActions extends sfActions
{
  public function executeIndex()
  {
    $this->commentList = $this->getCommentTable()->findAll();
  }

  public function executeCreate()
  {
    $this->form = new CommentForm();

    $this->setTemplate('edit');
  }

  public function executeEdit($request)
  {
    $this->form = $this->getCommentForm($request->getParameter('id'));
  }

  public function executeUpdate($request)
  {
    $this->forward404Unless($request->isMethod('post'));

    $this->form = $this->getCommentForm($request->getParameter('id'));

    $this->form->bind($request->getParameter('comment'));
    if ($this->form->isValid())
    {
      $comment = $this->form->save();

      $this->redirect('comment/edit?id='.$comment->get('id'));
    }

    $this->setTemplate('edit');
  }

  public function executeDelete($request)
  {
    $this->forward404Unless($comment = $this->getCommentById($request->getParameter('id')));

    $comment->delete();

    $this->redirect('comment/index');
  }
  
  private function getCommentTable()
  {
    return Doctrine::getTable('Comment');
  }
  
  private function getCommentById($id)
  {
    return $this->getCommentTable()->find($id);
  }
  
  private function getCommentForm($id)
  {
    $comment = $this->getCommentById($id);
    
    if ($comment instanceof Comment)
    {
      return new CommentForm($comment);
    }
    else
    {
      return new CommentForm();
    }
  }
}